package beans

import java.io.BufferedReader
import java.util.Random

import com.typesafe.config.{Config, ConfigFactory}

import scala.collection.immutable
import scala.io.Source

/**
  * Created by hunter.coder 涛哥  
  * 2019/2/11 14:21
  * 交流qq:657270652
  * Version: 1.0
  * 更多学习资料：https://blog.csdn.net/coderblack/
  * Description: 页面元素封装实体
  **/
class Page(val pgId: String,val pgSkuId: String,val pgUrl: String,val pgTitle: String,val pgAds: List[String],val pgActs: List[String]) {}


object Page {

  def getPagList():Map[String,Page] = {
    val config: Config = ConfigFactory.load()
    val pageFile: String = config.getString("dicts.pages")
    val source = Source.fromFile(pageFile)
    val lines = source.getLines()
    var pages = List[Page]()
    var pgMap = Map.empty[String,Page]

    for (elem <- lines) {

      val split = elem.split("\001")
      val url = split(0)
      val skuid = url.substring(url.lastIndexOf("/")+1,url.length)

      val title = split(1)
      val pgid = split(2)

      // 如果是“非广告”页本身，则为页面生成随机广告（广告总种类被代码写死限定在6中以内）
      var ads = List[String]()
      if(pgid.toInt>0 && pgid.toInt<20000) {
        // 为页面随机生成几个广告
        val rd = new Random()
        val size1 = rd.nextInt(2)
        val size2 = rd.nextInt(6)
        ads = (for (i <- size1 to size2) yield "ad0"+i).toList
      }

      // 如果是“非活动”页本身，则为页面生成随机活动（广告总种类被代码写死限定在6中以内）
      var acts = List[String]()
      if(pgid.toInt>0 && pgid.toInt<20000) {
        // 为页面随机生成几个活动
        val rd = new Random()
        val size1 = rd.nextInt(2)
        val size2 = rd.nextInt(6)
        acts = (for (i <- size1 to size2) yield "act0"+i).toList
      }

      // 封装页面各信息为page对象
      val page = new Page(pgid,skuid,url,title,ads,acts)
      pages :+= page
      pgMap += (pgid -> page)
    }
    pgMap
  }

  // 获取广告页面上的商品列表（由配置文件决定）
  def getAdItems(pgMap:Map[String,Page]):Map[String,List[String]] = {
    val config: Config = ConfigFactory.load()
    val adpFile: String = config.getString("dicts.adpages")
    val source = Source.fromFile(adpFile)
    val lines = source.getLines()
    var adMap = Map.empty[String,List[String]]
    for (elem <- lines) {
      val split = elem.split(",")

      var itemIds = List[String]()
      if(split.size>1){
        itemIds = split(1).split(":").toList
      }
      adMap += (split(0)->itemIds)
    }
    adMap
  }


  def main(args: Array[String]): Unit = {
    val pm = getPagList()
    println(getAdItems(pm))
  }

}
